package cn.edu.nuc.article.util;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.spec.SecretKeySpec;

public class test3 {
    public static void main(String[] args) throws Exception {
        // 生成密钥
        String key = "05d986b1141227cb20d46d0b5687c4f5";
        byte[] keyData = ByteUtils.fromHexString(key);

        System.out.println("=========加密===========");
        /* 加密 */
        // 创建并初始化密码器
        Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding", BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(keyData, "SM4");
        cipher.init(Cipher.ENCRYPT_MODE, sm4Key);
        // 创建输入流
        FileInputStream in = new FileInputStream("D:\\bjsasc\\test\\test.txt");// 创建要加密的输入流
        CipherInputStream cin = new CipherInputStream(in, cipher);// 再由密码器输入流把输入流和密码器包装
        FileOutputStream out = new FileOutputStream("D:\\bjsasc\\test\\enctest.txt");// 将密文保存到指定的文件中

        int b = 0;
        int i = 1;
        System.out.println("对文件输入流加密的密文如下：");
        while ((b = cin.read()) != -1) {// 读取输入流
            out.write((byte) b);// 把加密的输入流存入文件E_InStream.dat中
            System.out.print((byte) b + " ");
            i++;
            if (i % 30 == 0)
                System.out.println();

        }
        System.out.println();
        System.out.println("=========解密===========");
        /* 解密 */
        // 创建并初始化密码器
        Cipher deccipher = Cipher.getInstance("SM4/ECB/PKCS5Padding", BouncyCastleProvider.PROVIDER_NAME);
        Key sm4decKey = new SecretKeySpec(keyData, "SM4");
        deccipher.init(Cipher.ENCRYPT_MODE, sm4decKey);
        FileInputStream fin = new FileInputStream("D:\\bjsasc\\test\\enctest.txt");// 获取要解密的文件
        CipherInputStream cipherin = new CipherInputStream(fin, deccipher);
        int c = 0;
        while ((c = cipherin.read()) != -1) {// 读取输入流
            System.out.print((char) c);
        }

        /*int d = 0;
        int z = 1;
        while ((d = cipherin.read()) != -1) {// 读取输入流
            out.write((char) d);// 把加密的输入流存入文件E_InStream.dat中
            System.out.print((char) d + " ");
            z++;
            if (z % 30 == 0)
                System.out.println();

        }
        System.out.println();*/
        //关闭流
        in.close();
        cin.close();
        out.close();
        cipherin.close();
    }
}
